
(function() {

    /*
     * JSON receive {
     *      act: "position"|"fire"
     *      -----
     *      x: 
     *      y:
     *      -----
     *      x:
     *      y:
     *      
     *      
     * 
     * }
     * 
     * JSON sent {
     *      act:
     *      ----
     *      id:
     *      ----
     *      life:
     *      enemies:[{
     *          life:
     *          x:
     *          y:
     *      }]
     * }
     * 
     * 
     */

    var WebSocketServer = require('ws').Server;
    var wss = new WebSocketServer({port: 666});
    var IDs = [];

    wss.on('connection', function(socket) {
        socket.on('message', function(message, flags) {
            if (!flags.binary) {
                var obj = JSON.parse(message);
                
                if(obj.act === "fire"){
                    console.log("fogo!!!");
                }
            }
        });
        socket.on('close', function() {
            for (var i in wss.clients)
                wss.clients[i].send('{"nusu":' + wss.clients.length + ',"act":"nusu"}');
        });
        var aceito = false, id;
        while (!aceito) {
            id = Math.floor(Math.random() * 5000000);
            if (IDs.indexOf(id) === -1) {
                IDs.push(id);
                aceito = true;
            }
        }
        socket.send('{"id":' + id + ', "act":"id"}');
        socket.id = id;
        console.log("usuário conectado com id: " + id);
        for (var i in wss.clients)
            wss.clients[i].send('{"nusu":' + wss.clients.length + ',"act":"update"}');
    });



})();